﻿//-----------------------------------------------------------------------
// <copyright file="ClientVersionHelper.cs" company="AFS">
// Copyright (c) AFS. All rights reserved.
//
//    This file is part of Chatbox.
//
//    Chatbox is free software: you can redistribute it and/or modify
//    it under the terms of the GNU Lesser General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    any later version.
//
//    Chatbox is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//    GNU Lesser General Public License for more details.
//
//    You should have received a copy of the GNU Lesser General Public License
//    along with Chatbox. If not, see http://www.gnu.org/copyleft/lesser.html
// </copyright>
//----------------------------------------------------------------------- 

namespace ChatBox.DomainObjects.XmlFeedObjects
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;

    using Utility;

    /// <summary>
    /// Helper for the client version XML feed
    /// </summary>
    public static class ClientVersionHelper
    {
        /// <summary>
        /// Read client versions from xml
        /// </summary>
        /// <param name="doc">the xml to read</param>
        /// <returns>a list of client versions</returns>
        public static IEnumerable<ClientVersion> ToClientVersions(this XContainer doc)
        {
            var versionElements = doc.Elements("clientregistry").Elements("client");

            var versionList =
                from version in versionElements
                select new ClientVersion
                {
                    Id = version.Attribute("client_id").Value.ToInteger(),
                    ClientClass = version.Attribute("client_class").Value,
                    LatestVersion = version.Element("version").Value,
                    Homepage = version.Element("homepage").Value,
                    Download = version.Element("download").Value,
                    Maintainer = version.Element("maintainer").ToLink()
                };

            return versionList.ToList();
        }

        /// <summary>
        /// Get a client version from the list by name
        /// </summary>
        /// <param name="versions">the versions to search</param>
        /// <param name="name">the name to find</param>
        /// <returns>the version wit the specifed name</returns>
        public static ClientVersion FindByName(this IEnumerable<ClientVersion> versions, string name)
        {
            return (from version in versions 
                where version.ClientClass == name 
                select version).SingleOrDefault();
        }
    }
}
